package com.itwenke.springbootdemo.shirowebboot.session;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisSessionDAO extends AbstractSessionDAO {

    private final String SHIOR_SESSION = "session:";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        redisTemplate.opsForValue().set(SHIOR_SESSION + sessionId, session, 30, TimeUnit.MINUTES);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if (sessionId == null) {
            return null;
        }
        Session session = (Session) redisTemplate.opsForValue().get(SHIOR_SESSION + sessionId);
        if (session != null) {
            redisTemplate.expire(SHIOR_SESSION + sessionId,30,TimeUnit.MINUTES);
        }
        return session;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session == null) {
            return;
        }
        redisTemplate.opsForValue().set(SHIOR_SESSION + session.getId(), session, 30, TimeUnit.MINUTES);
    }

    @Override
    public void delete(Session session) {
        if (session == null) {
            return;
        }
        redisTemplate.delete(SHIOR_SESSION + session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<String> keys = redisTemplate.keys(SHIOR_SESSION + "*");
        Set<Session> sessionSet = new HashSet<>();

        // 使用Redis管道
        List<Object> results = redisTemplate.executePipelined((RedisConnection connection) -> {
            for (String key : keys) {
                connection.get(key.toString().getBytes());
            }
            return null;
        });

        // 处理管道返回的结果
        for (Object result : results) {
            if (result != null) {
                Session session = (Session) result;
                sessionSet.add(session);
            }
        }

        return sessionSet;
    }
}
